package com.software.loginregister.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.software.loginregister.entity.vo.UserUpdateDTO;

/**
 * SharedPreferences 工具类
 * 用于管理用户登录状态和个人信息
 */
public class SharedPreferencesUtil {
    private static final String TAG = "SharedPreferencesUtil";

    // SharedPreferences 文件名
    private static final String PREF_LOGIN = "LoginPreferences";
    private static final String PREF_USER = "UserPreferences";

    // 登录相关的键名常量
    private static final String KEY_REMEMBER = "remember";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_PASSWORD = "password";
    private static final String KEY_USER_ID = "userId";
    private static final String KEY_IS_LOGIN = "isLogin";
    private static final String KEY_LOGIN_TIME = "loginTime";

    // 用户信息相关的键名常量
    private static final String KEY_NICKNAME = "nickname";
    private static final String KEY_SIGNATURE = "signature";
    private static final String KEY_AVATAR = "avatar";
    private static final String KEY_GENDER = "gender";
    private static final String KEY_AGE = "age";
    private static final String KEY_PHONE = "phone";
    //口味选择
    private static final String PREF_NAME = "app_preferences";
    private static final String KEY_IS_LOGGED_IN = "is_logged_in";
    private static final String KEY_TASTE_SELECTED = "taste_selected";

    // 登录状态有效期（7天）
    private static final long LOGIN_VALID_TIME = 7 * 24 * 60 * 60 * 1000;
    private static final String PREF_NAMES = "user_preferences";
    private static final String KEY_TASTE_PREFERENCES = "taste_preferences";

    /**
     * 获取登录相关的SharedPreferences实例
     */
    private static SharedPreferences getLoginPreferences(Context context) {
        return context.getSharedPreferences(PREF_LOGIN, Context.MODE_PRIVATE);
    }

    /**
     * 获取用户信息相关的SharedPreferences实例
     */
    private static SharedPreferences getUserPreferences(Context context) {
        return context.getSharedPreferences(PREF_USER, Context.MODE_PRIVATE);
    }

    /**
     * 保存登录状态和基本用户信息
     */
    public static void saveLoginStatus(Context context, boolean remember,
                                       String username, String password, Long userId) {
        try {
            Log.d("LoginDebug", "开始保存登录状态 - userId: " + userId);
            SharedPreferences.Editor editor = getLoginPreferences(context).edit();
            editor.putBoolean(KEY_IS_LOGIN, true)
                    .putBoolean(KEY_REMEMBER, remember)
                    .putString(KEY_USERNAME, username)
                    .putLong(KEY_LOGIN_TIME, System.currentTimeMillis());

            if (remember) {
                editor.putString(KEY_PASSWORD, password);
            }

            if (userId != null) {
                editor.putLong(KEY_USER_ID, userId);
                Log.d("LoginDebug", "正在保存userId: " + userId);
            } else {
                editor.remove(KEY_USER_ID);
                Log.d("LoginDebug", "userId为空，移除KEY_USER_ID");
            }

            editor.apply();
            Log.d("LoginDebug", "登录状态保存完成");
        } catch (Exception e) {
            Log.e(TAG, "保存登录状态失败", e);
        }
    }


    /**
     * 获取用户ID (Long类型)
     * 添加兼容性处理，支持从int类型转换
     */
    public static Long getUserId(Context context) {
        try {
            SharedPreferences sp = getLoginPreferences(context);
            Log.d("LoginDebug", "正在获取用户ID");
            // 尝试获取Long类型
            try {
                long userId = sp.getLong(KEY_USER_ID, -1L);
                Log.d("LoginDebug", "获取到的userId(Long): " + (userId != -1L ? userId : "未找到"));
                return userId != -1L ? userId : null;
            } catch (ClassCastException e) {
                Log.d("LoginDebug", "Long类型获取失败，尝试获取Int类型");
                // 如果是Integer类型，进行兼容处理
                int intUserId = sp.getInt(KEY_USER_ID, -1);
                if (intUserId != -1) {
                    long longUserId = (long) intUserId;
                    Log.d("LoginDebug", "从Int转换到Long: " + longUserId);
                    sp.edit().putLong(KEY_USER_ID, longUserId).apply();
                    return longUserId;
                }
                Log.d("LoginDebug", "未找到用户ID");
                return null;
            }
        } catch (Exception e) {
            Log.e(TAG, "获取用户ID失败", e);
            return null;
        }
    }


    /**
     * 迁移旧版本数据到新版本
     * 可以在应用启动时调用
     */
    public static void migrateData(Context context) {
        try {
            SharedPreferences sp = getLoginPreferences(context);
            // 检查是否需要迁移
            try {
                sp.getLong(KEY_USER_ID, -1L);
                // 如果没有异常，说明已经是Long类型，不需要迁移
            } catch (ClassCastException e) {
                // 需要迁移
                int intUserId = sp.getInt(KEY_USER_ID, -1);
                if (intUserId != -1) {
                    sp.edit()
                            .putLong(KEY_USER_ID, (long) intUserId)
                            .apply();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "数据迁移失败", e);
        }
    }
    /**
     * 保存用户详细信息
     */
    public static void saveUserInfo(Context context, UserUpdateDTO userInfo) {
        try {
            SharedPreferences.Editor editor = getUserPreferences(context).edit();
            editor.putString(KEY_NICKNAME, userInfo.getNickname())
                    .putString(KEY_SIGNATURE, userInfo.getSignature())
                    .putInt(KEY_GENDER, userInfo.getGender())
                    .putInt(KEY_AGE, userInfo.getAge())
                    .putString(KEY_PHONE, userInfo.getPhone())
                    .putString(KEY_AVATAR, userInfo.getAvatar());

            editor.apply();
        } catch (Exception e) {
            Log.e(TAG, "保存用户信息失败", e);
        }
    }

    /**
     * 获取保存的用户详细信息
     */
    public static UserUpdateDTO getUserInfo(Context context) {
        try {
            SharedPreferences sp = getUserPreferences(context);
            UserUpdateDTO userInfo = new UserUpdateDTO();
            userInfo.setUserId(getUserId(context));  // 直接使用Long类型
            userInfo.setNickname(sp.getString(KEY_NICKNAME, ""));
            userInfo.setSignature(sp.getString(KEY_SIGNATURE, ""));
            userInfo.setGender(sp.getInt(KEY_GENDER, 0));
            userInfo.setAge(sp.getInt(KEY_AGE, 0));
            userInfo.setPhone(sp.getString(KEY_PHONE, ""));
            return userInfo;
        } catch (Exception e) {
            Log.e(TAG, "获取用户信息失败", e);
            return null;
        }
    }

    /**
     * 清除所有用户数据
     */
    public static void clearAllUserData(Context context) {
        try {
            // 清除登录信息
            getLoginPreferences(context).edit().clear().apply();
            // 清除用户详细信息
            getUserPreferences(context).edit().clear().apply();
        } catch (Exception e) {
            Log.e(TAG, "清除用户数据失败", e);
        }
    }

    /**
     * 检查登录状态是否有效
     */
    public static boolean isLoggedIn(Context context) {
        try {
            SharedPreferences sp = getLoginPreferences(context);
            if (!sp.getBoolean(KEY_IS_LOGIN, false)) {
                return false;
            }

            long loginTime = sp.getLong(KEY_LOGIN_TIME, 0);
            long currentTime = System.currentTimeMillis();
            if (currentTime - loginTime > LOGIN_VALID_TIME) {
                clearAllUserData(context);
                return false;
            }
            return true;
        } catch (Exception e) {
            Log.e(TAG, "检查登录状态失败", e);
            return false;
        }
    }

    // 其他 getter 方法
    public static boolean isRemembered(Context context) {
        return getLoginPreferences(context).getBoolean(KEY_REMEMBER, false);
    }

    public static String getUsername(Context context) {
        return getLoginPreferences(context).getString(KEY_USERNAME, "");
    }

    public static String getPassword(Context context) {
        return getLoginPreferences(context).getString(KEY_PASSWORD, "");
    }


    /**
     * 更新登录时间
     */
    public static void updateLoginTime(Context context) {
        try {
            getLoginPreferences(context).edit()
                    .putLong(KEY_LOGIN_TIME, System.currentTimeMillis())
                    .apply();
        } catch (Exception e) {
            Log.e(TAG, "更新登录时间失败", e);
        }
    }
    // 设置口味选择状态
    public static void setTasteSelected(Context context, boolean selected) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putBoolean(KEY_TASTE_SELECTED, selected).apply();
    }

    // 获取口味选择状态
    public static boolean isTasteSelected(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        return prefs.getBoolean(KEY_TASTE_SELECTED, false);
    }

    public static void saveConversationId(Context context, String conversationId) {
        if (context != null) {
            SharedPreferences sp = context.getSharedPreferences("chat_info", Context.MODE_PRIVATE);
            sp.edit().putString("current_conversation_id", conversationId).apply();
        }
    }

    public static String getConversationId(Context context) {
        if (context != null) {
            SharedPreferences sp = context.getSharedPreferences("chat_info", Context.MODE_PRIVATE);
            return sp.getString("current_conversation_id", null);
        }
        return null;
    }

    public static void clearConversationId(Context context) {
        if (context != null) {
            SharedPreferences sp = context.getSharedPreferences("chat_info", Context.MODE_PRIVATE);
            sp.edit().remove("current_conversation_id").apply();
        }
    }
    // 保存饮食偏好
    public static void saveTastePreferences(Context context, String preferences) {
        SharedPreferences sp = context.getSharedPreferences(PREF_NAMES, Context.MODE_PRIVATE);
        sp.edit().putString(KEY_TASTE_PREFERENCES, preferences).apply();
    }
    // 获取饮食偏好
    public static String getTastePreferences(Context context) {
        SharedPreferences sp = context.getSharedPreferences(PREF_NAMES, Context.MODE_PRIVATE);
        return sp.getString(KEY_TASTE_PREFERENCES, "");
    }
    // 清除饮食偏好
    public static void clearTastePreferences(Context context) {
        SharedPreferences sp = context.getSharedPreferences(PREF_NAMES, Context.MODE_PRIVATE);
        sp.edit().remove(KEY_TASTE_PREFERENCES).apply();
    }

    public static void saveUserAvatar(Context context, String avatarUrl) {
        SharedPreferences sp = context.getSharedPreferences("user_info", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("avatar_url", avatarUrl);
        editor.apply();
    }

    public static String getUserAvatar(Context context) {
        SharedPreferences sp = context.getSharedPreferences("user_info", Context.MODE_PRIVATE);
        return sp.getString("avatar_url", "");
    }
}